package com.leilei.metrics;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Counter;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
import org.apache.flink.streaming.api.functions.windowing.RichAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lei
 * @version 1.0
 * @date 2021/3/29 22:10
 * @desc Metrics 监控
 */
public class FlinkMetrics {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        DataStreamSource<String> streamSource = env.addSource(new MySource());
        AllWindowedStream<String, TimeWindow> windowAll = streamSource.
                windowAll(SlidingProcessingTimeWindows.of(Time.seconds(5), Time.seconds(2)));
        SingleOutputStreamOperator<String> result = windowAll.apply(new MySlidingWindow());
        result.print();
        env.execute("metrics-one");
    }

    public static class MySlidingWindow extends RichAllWindowFunction<String, String, TimeWindow> {
        Counter counter;

        @Override
        public void apply(TimeWindow window, Iterable<String> values, Collector<String> out) throws Exception {
            for (String value : values) {
                counter.inc();
                out.collect(value);
            }
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            counter = getRuntimeContext().getMetricGroup().addGroup("test-metric").counter("uuid-count");
        }
    }

    public static class MySource extends RichSourceFunction<String> {
        AtomicInteger ato = new AtomicInteger();

        @Override
        public void run(SourceContext<String> ctx) throws Exception {
            while (true) {
                String uuid = UUID.randomUUID().toString();
                ctx.collect(uuid + ato.getAndIncrement());
                Thread.sleep(5000);
            }
        }

        @Override
        public void cancel() {

        }
    }
}

